<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Home' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main">
      <el-row>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加用户</el-button
        >
      </el-row>
      <template>
        <el-collapse style="border: none; background-color: wheat">
          <el-table
            :data="tableData"
            border
            style="width: 100%; margin: 20px 0"
          >
          <!-- 下拉列表 -->
            <el-table-column
              prop=""
              label=""
              type="expand"
              expand-row-keys
              width="60"
            >
              <template slot-scope="{ row: { id, children } }">
                <el-row
                  v-for="item in children"
                  :key="item.id"
                  style="border: 1px solid whitesmoke; margin: 25px"
                >
                  <el-col
                    class="el-col1"
                    :span="4"
                    style="border: 1px solid whitesmoke"
                  >
                    <el-tag closable @close="deleteuser(item.id, id)">
                      {{ item.authName }}
                    </el-tag>
                    <i
                      class="el-icon-caret-right"
                      v-if="item.children.length !== 0"
                    ></i>
                  </el-col>
                  <el-col :span="20">
                    <el-row v-for="list in item.children" :key="list.id">
                      <el-col :span="4" class="el-col2">
                        <el-tag
                          closable
                          @close="deleteuser(list.id, id)"
                          type="success"
                          >{{ list.authName }}</el-tag
                        >
                        <i
                          class="el-icon-caret-right"
                          v-if="list.children.length !== 0"
                        ></i>
                      </el-col>
                      <el-col :span="20">
                        <el-tag
                          class="el-col3"
                          closable
                          @close="deleteuser(add.id, id)"
                          type="warning"
                          v-for="add in list.children"
                          :key="add.id"
                          >{{ add.authName }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <el-row v-if="children.length === 0">
                  <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="" type="index" label="*" width="60">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" min-width="180">
            </el-table-column>
            <el-table-column prop="roleDesc" label="角色叙述" min-width="180">
            </el-table-column>
            <el-table-column label="操作" min-width="230">
              <template slot-scope="scope">
                <el-button
                  type="success"
                  @click="SelectFormVisibles(scope.row)"
                >
                  <i class="el-icon-edit"></i>
                  编辑
                </el-button>
                <el-button type="danger" @click="dialogVisibles(scope.row.id)">
                  <i class="el-icon-delete-solid"></i>删除</el-button
                >
                <!-- DistUser -->
                <el-button type="warning" @click="showDialog(scope.row)"
                  ><i class="el-icon-s-tools"></i>分配权限</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-collapse>
      </template>
      <!-- 添加用户弹框 -->
      <!-- :rules="rules" -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="form">
          <el-form-item
            label="用户名称"
            prop="roleName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="用户叙述"
            prop="roleDesc"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="roleAdd">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑用户 -->
      <el-dialog title="编辑用户" :visible.sync="selectFormVisible">
        <el-form :model="upDateform" ref="form">
          <el-form-item
            label="用户名称"
            prop="roleName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="upDateform.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户叙述"
            prop="roleDesc"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="upDateform.roleDesc"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="roleUpdate">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 删除弹框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <span>确定要永久删除这条数据吗！</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="DeleteRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <!-- DistFormVisible -->

      <el-dialog title="权限分配" :visible.sync="DistFormVisible">
        <div class="tree-container">
          <el-tree
            :data="DataList"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="selectedRights"
            :expand-on-click-node="false"
            :props="defaultProps"
            ref="rightsTree"
          >
          </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="DistFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="DistRoles">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  RoleAddUser,
  RoleUser,
  UpdateRole,
  DeleteRole,
  RoleList,
  granRoleRight,
  delTagRoleright,
} from "../../api/index.js";
export default {
  name: "",
  data() {
    return {
      tableData: [
        {
          id: 0,
          roleName: "",
          roleDesc: "",
        },
      ],
      dialogFormVisible: false,
      formLabelWidth: "200",
      selectFormVisible: false,
      dialogVisible: false,
      DistFormVisible: false,

      form: {
        id: 0,
        roleName: "",
        roleDesc: "",
      },
      upDateform: {
        id: 0,
        roleName: "",
        roleDesc: "",
      },
      rolsId: 0,
      // 权限分配
      DataList: [],
      DataListRights: [],
      selectedRights: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
    };
  },
  created() {
    this.getRoleUser();
  },

  methods: {
    // 页面数据渲染
    async getRoleUser() {
      let { data } = await RoleUser();
      this.tableData = data;
    },

    // 添加用户
    async roleAdd() {
      let {
        meta: { msg, status },
      } = await RoleAddUser(this.form);
      if (status == 201) {
        this.$message({ type: "success", message: msg });
        this.getRoleUser();
      } else {
        this.$message({ type: "info", message: "创建失败" });
      }
      this.dialogFormVisible = false;
    },
    // 编辑用户
    SelectFormVisibles({ id, roleDesc, roleName }) {
      this.upDateform.id = id;
      this.upDateform.roleDesc = roleDesc;
      this.upDateform.roleName = roleName || "";
      console.log(this.upDateform);
      this.selectFormVisible = true;
    },
    async roleUpdate() {
      let res = await UpdateRole(this.upDateform);
      this.getRoleUser();
      this.selectFormVisible = false;
      console.log(res);
    },
    // 删除
    dialogVisibles(id) {
      this.rolsId = id;
      this.dialogVisible = true;
    },
    async DeleteRoles() {
      let {
        meta: { msg, status },
      } = await DeleteRole(this.rolsId);
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        this.getRoleUser();
        this.dialogVisible = false;
      } else {
        this.$message({ type: "warning", message: "删除失败！" });
      }
    },

    // 权限分配
    // 发送请求
    async showDialog(row) {
      this.DistFormVisible = true;
      // 权限数据初步显示
      // 遍历之前先让数组清空
      this.selectedRights.length = 0;
      // 取出当前点击角色的所有权限， 然后遍历到它的第三个children，取出它里面的所有的项的id，存进selectedRights中
      // 1. 遍历第一个children取出一级权限
      row.children.forEach((first) => {
        if (first.children && first.children.length !== 0) {
          // 2. 遍历第二个children取出二级权限
          first.children.forEach((second) => {
            if (second.children && second.children.length !== 0) {
              // 3. 遍历第三个children取出三级权限
              second.children.forEach((third) => {
                this.selectedRights.push(third.id);
              });
            }
          });
        }
      });
      this.rolsId = row.id;

      let { data } = await RoleList("tree");
      this.DataList = data;
    },
    async DistRoles() {
      let res = this.$refs["rightsTree"].getHalfCheckedKeys();
      let add = this.$refs["rightsTree"].getCheckedKeys();
      let result = `${res.join(",")},${add.join(",")}`;

      let obj = {
        roleid: this.rolsId,
        rids: result,
      };
      let {
        meta: { msg, status },
      } = await granRoleRight(obj);
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        this.getRoleUser();
      } else {
        this.$message({ type: "warning", message: "分配权限失败！" });
      }
      // console.log(this.selectedRights);
      this.DistFormVisible = false;
    },
    // 移出权限
    async deleteuser(id, roleid) {
      let obj = {
        roleid,
        rightid: id,
      };
      let res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (!res) return this.$message.info("取消删除");
      let {data,
        meta: { msg, status },
      } = await delTagRoleright(obj);
        status == 200?this.$message.success(msg):this.$message.warning(msg);
        this.tableData.forEach(item=>{
          if(item.id == roleid){
            
            item.children = data
          }
        })
    },
  },
};
</script>

<style scoped lang='css'>
.main {
  padding: 25px;
  background-color: #fff;
}
.el-breadcrumb {
  background-color: #eaedf1;
}
.displays {
  display: flex;
  min-width: 200px;
}
.el-row {
  display: flex;
  min-width: 400px;
}
.el-breadcrumb {
  padding-left: 0;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  border: 1px solid whitesmoke;
}
.el-col1,
.el-col2 {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-col3 {
  margin: 5px 10px;
}
</style>